﻿using UAParser;

namespace Shared.Http.UserAgentParser
{
    public class UserAgentParser : IUserAgentParser
    {
        public UserAgentInfo Parse(string userAgent)
        {
            if (string.IsNullOrWhiteSpace(userAgent))
            {
                return new UserAgentInfo(
                    deviceType: "Unknown",
                    operatingSystem: "Unknown",
                    browser: "Unknown",
                    rawUserAgent: string.Empty,
                    isBot: false
                );
            }
            var client = Parser.GetDefault().Parse(userAgent);

            string deviceType = GetDeviceType(client.Device, client.OS.Family);
            return new UserAgentInfo(
                deviceType: deviceType,
                operatingSystem: client.OS.Family ?? "UNKNOWN",
                browser: client.UA.Family ?? "UNKNOWN",
                rawUserAgent: userAgent,
                isBot: IsBot(client)
            )
            {
                OsVersion = GetVersionString(client.OS.Major, client.OS.Minor, client.OS.Patch),
                BrowserVersion = GetVersionString(client.UA.Major, client.UA.Minor, client.UA.Patch),
                DeviceBrand = client.Device?.Brand ?? "UNKNOWN",
                DeviceModel = client.Device?.Model ?? "UNKNOWN"
            };
        }

        private static string GetDeviceType(Device device, string osFamily)
        {
            //先看设备信息
            if (device?.Family != null)
            {
                var family = device.Family.ToLowerInvariant();
                if (family.Contains("iphone") || family.Contains("android"))
                    return DeviceTypes.Mobile;
                if (family.Contains("ipad"))
                    return DeviceTypes.Tablet;
                if (family == "spider" || family.Contains("bot"))
                    return DeviceTypes.Bot;
            }

            //看操作系统
            if (osFamily != null)
            {
                var os = osFamily.ToLowerInvariant();
                if (os == "ios" || os == "android")
                    return DeviceTypes.Mobile;
                if (os == "windows" || os == "macos" || os == "linux")
                    return DeviceTypes.Desktop;
            }

            return DeviceTypes.Unknown;
        }


        /// <summary>
        /// 判断是否为机器人
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        private static bool IsBot(ClientInfo client)
        {
            if (client.Device?.Family?.Equals("Spider", StringComparison.OrdinalIgnoreCase) == true)
                return true;
            if (client.UA.Family?.IndexOf("bot", StringComparison.OrdinalIgnoreCase) >= 0)
                return true;
            return false;
        }

        /// <summary>
        /// 获取版本号
        /// </summary>
        /// <param name="major"></param>
        /// <param name="minor"></param>
        /// <param name="patch"></param>
        /// <returns></returns>
        private static string GetVersionString(string major, string minor, string patch)
        {
            if (string.IsNullOrEmpty(major)) return "UNKNOWN";
            if (string.IsNullOrEmpty(minor)) return major;
            if (string.IsNullOrEmpty(patch)) return $"{major}.{minor}";
            return $"{major}.{minor}.{patch}";
        }
    }
}
